package cn.tedu.loding.service.impl;

import cn.tedu.loding.ex.ServiceException;
import cn.tedu.loding.mapper.CartMapper;
import cn.tedu.loding.mapper.OrderMapper;
import cn.tedu.loding.mapper.ProductMapper;
import cn.tedu.loding.pojo.dto.OrderAddNewDTO;
import cn.tedu.loding.pojo.entity.Order;
import cn.tedu.loding.pojo.entity.Product;
import cn.tedu.loding.pojo.vo.OrderListItemVO;
import cn.tedu.loding.pojo.vo.OrderStandardVO;
import cn.tedu.loding.pojo.vo.ProductStandardVO;
import cn.tedu.loding.service.IOrderService;
import cn.tedu.loding.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理订单数据的业务实现类
 *
 */
@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CartMapper cartMapper;

    public OrderServiceImpl() {
        log.debug("创建业务对象：OrderServiceImpl");
    }

    public PageInfo<OrderListItemVO> getAllOrderByPage(Integer page, Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<OrderListItemVO> list= orderMapper.list();

        return new PageInfo<>(list);
    }

    @Override
    public void addNew(OrderAddNewDTO orderAddNewDTO) {
        log.debug("开始处理【添加订单】的业务，参数：{}", orderAddNewDTO);
        Long userId = orderAddNewDTO.getUserId();
        Long productId = orderAddNewDTO.getProductId();

        //减库存
        ProductStandardVO productStandardVO = productMapper.getStandardById(productId);
        if(productStandardVO == null){
            String message = "新增订单失败，您选择的商品不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        Long reduceCount = orderAddNewDTO.getCount();
        if(reduceCount > productStandardVO.getStock()){
            String message = "新增订单失败，商品库存不足！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, message);
        }
        Product product = new Product();
        product.setId(productId);
        product.setStock(productStandardVO.getStock()-reduceCount);
        int rows = productMapper.update(product);
        if (rows != 1) {
            String message = "新增订单失败，库存更新失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("库存减少成功！");

        //删购物车
        cartMapper.deleteByUserIdAndProductId(userId,productId);

        //增订单
        Order order = new Order();
        BeanUtils.copyProperties(orderAddNewDTO,order);
        rows = orderMapper.insert(order);
        if (rows != 1) {
            String message = "新增订单失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("插入订单数据完成");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据id删除订单】的业务，参数：{}", id);
        OrderStandardVO order = orderMapper.getStandardById(id);
        if(order == null){
            String message = "删除订单失败，此订单不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //加库存
        Long productId = order.getProductId();
        Long count = order.getCount();
        ProductStandardVO productStandardVO = productMapper.getStandardById(productId);
        Product product = new Product();
        product.setId(productId);
        product.setStock(productStandardVO.getStock()+count);
        int rows = productMapper.update(product);
        if (rows != 1) {
            String message = "删除订单失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

        //删订单
        rows = orderMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除订单失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public OrderStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据id查询订单详情】的业务，参数：{}", id);
        OrderStandardVO order = orderMapper.getStandardById(id);
        if (order == null) {
            String message = "获取订单详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return order;
    }

    @Override
    public List<OrderListItemVO> list() {
        log.debug("开始处理【查询订单列表】的请求,无参数");
        return orderMapper.list();
    }

    @Override
    public List<OrderListItemVO> listByUserId(Long userId) {
        log.debug("开始处理【查询指定用户订单列表】的请求：{}",userId);
        return orderMapper.listByUserId(userId);
    }

}
